<?php

namespace App\Exceptions;

use App\Http\Response;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param Exception $exception
     * @return mixed|void
     * @throws Exception
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param \Illuminate\Http\Request $request
     * @param Exception $exception
     * @return \Symfony\Component\HttpFoundation\Response|static|Response
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof HttpException) {
            $message = empty($exception->getMessage()) ? null : $exception->getMessage();
            switch ($exception->getStatusCode()) {

                case 401:
                    return Response::error(BusinessException::UNAUTHORIZED, $message ?? '没有授权', 401);
                    break;
                case 403:
                    return Response::error(BusinessException::FORBIDDEN, $message ?? '没有权限', 403);
                    break;
                case 404:
                    return Response::error(BusinessException::RESOURCE_NOT_FOUND, $message ?? '资源没有找到', 404);
                    break;
                case 500:
                    return Response::error(BusinessException::SERVER_ERROR, $message ?? '服务器异常', 500);
                    break;
            }
        }

        if ($exception instanceof BusinessException) {
            return Response::error($exception->getBusinessCode(), $exception->getMessage());
        }
        if ($exception instanceof ValidatorException) {
            $validator = $exception->validator();
            if ($validator->fails()) {
                $erorrs = [];
                foreach ($validator->errors()->all() as $key => $message) {
                    $erorrs[] = [
                        'code' => BusinessException::PARAMETER_ERROR,
                        'message' => $message
                    ];
                }
                return Response::errors($erorrs, 422);
            }
        }

        return parent::render($request, $exception);
    }
}
